<template>
  <div class="app-container">

    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="计划编号" prop="planCode">
          <el-input
            v-model="queryParams.planCode"
            placeholder="请输入计划编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="计划月份" prop="planMonth">
          <el-date-picker
            clearable
            v-model="queryParams.planMonth"
            type="month"
            placeholder="请选择计划月份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划状态" prop="planStatus">
          <el-select v-model="queryParams.planStatus" placeholder="请选择计划状态" clearable>
            <el-option label="草稿" value="草稿" />
            <el-option label="待审批" value="待审批" />
            <el-option label="已审批" value="已审批" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['xs:plan:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['xs:plan:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="planList" border>

        <el-table-column label="计划编号" align="center" prop="planCode" >
          <template slot-scope="scope">
            <el-button
                type="text"
                @click="handleView(scope.row)"
                v-hasPermi="['xs:plan:query']"
            >{{scope.row.planCode}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="计划名称" align="center" prop="planName" />
        <el-table-column label="总金额（元）" align="center" prop="totalAmount">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.totalAmount">{{ formatCurrency(scope.row.totalAmount) }}</el-tag>
            <span v-else>{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划月份" align="center" prop="planMonth" />
        <el-table-column label="计划状态" align="center" prop="planStatus">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.planStatus === '草稿'" type="info">草稿</el-tag>
            <el-tag v-if="scope.row.planStatus === '待审批'" type="warning">待审批</el-tag>
            <el-tag v-if="scope.row.planStatus === '已审批'" type="success">已审批</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy"/>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-upload2"
              @click="handleSubmit(scope.row)"
              v-hasPermi="['xs:plan:edit']"
              v-if="scope.row.planStatus === '草稿'"
            >提交</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['xs:plan:edit']"
              v-if="scope.row.planStatus === '草稿'"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['xs:plan:remove']"
              v-if="scope.row.planStatus === '草稿'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>


    <!-- 添加或修改销售预测计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-card style="border-radius: 10px">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="预测计划号" prop="planCode">
                <el-input v-model="form.planCode" placeholder="请输入预测计划号" :readonly="optType === 'view'"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预测计划名称" prop="planName">
                <el-input v-model="form.planName" placeholder="请输入预测计划名称" :readonly="optType === 'view'"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划月份" prop="planMonth">
                <el-date-picker
                  clearable
                  v-model="form.planMonth"
                  type="month"
                  :disabled="optType === 'view'"
                  placeholder="请选择计划月份">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划人员" prop="salesPerson">
                <el-input v-model="form.salesPerson" placeholder="请输入计划人员" readonly>
                  <el-button
                      slot="append"
                      @click="handleSelectUser"
                      icon="el-icon-search"
                      v-if="optType !== 'view'">
                  </el-button>
                </el-input>
                <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" :readonly="optType === 'view'"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <el-card style="border-radius: 10px" v-if="form.planId !== null">
        <PlanLine
            ref="xsPlanLine"
            :planId="form.planId"
            :planCode="form.planCode"
            :optType="optType"
        ></PlanLine>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addPlan, delPlan, getPlan, listPlan, updatePlan} from "@/api/mes/xs/plan";
import {genCode} from "@/api/system/autocode/rule";
import UserSelect from "@/components/userSelect/single.vue";
import PlanLine from "./line.vue";

export default {
  name: "Plan",
  components: { UserSelect, PlanLine },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售预测计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: null,
        planName: null,
        totalAmount: null,
        planMonth: null,
        salesPerson: null,
        planStatus: null,
        remarks: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planCode: [
          { required: true, message: "计划编号不能为空", trigger: "blur" }
        ],
        planMonth: [
          { required: true, message: "计划月份不能为空", trigger: "blur" }
        ],
        salesPerson: [
          { required: true, message: "销售人员不能为空", trigger: "blur" }
        ]
      },
      optType: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询销售预测计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planCode: null,
        planName: null,
        totalAmount: null,
        planMonth: new Date(),
        salesPerson: null,
        planStatus: "草稿",
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('FORECAST_PLAN_CODE').then(response =>{
        this.form.planCode = response;
      });
      this.open = true;
      this.title = "添加销售预测计划";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售预测计划";
        this.optType = "update";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "销售预测计划查看";
        this.optType = "view";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let planMonthValue = this.form.planMonth;

          // 清空之前的值
          this.form.planMonth = null;

          if (planMonthValue) {
            let year, month;
            // 情况1：planMonth 是 Date 对象
            if (planMonthValue instanceof Date) {
              if (!isNaN(planMonthValue.getTime())) {
                year = planMonthValue.getFullYear();
                month = planMonthValue.getMonth() + 1;
              }
            }
            // 情况2：planMonth 是字符串，比如 '2025-07'
            else if (typeof planMonthValue === 'string') {
              const match = planMonthValue.match(/^(\d{4})-(\d{2})$/);
              if (match) {
                year = parseInt(match[1], 10);
                month = parseInt(match[2], 10);
              }
            }
            // 如果成功解析出年月
            if (year && month) {
              this.form.planMonth = `${year}-${String(month).padStart(2, '0')}`;
            }
          }

          if (this.form.planId != null) {
            // 防止二次修改总金额
            this.form.totalAmount = null;
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除销售预测计划编号为"' + planIds + '"的数据项？').then(function() {
        return delPlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xs/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮操作 **/
    handleSubmit(row) {
      this.$modal.confirm('是否确认提交编号为"' + row.planCode + '"的销售预测计划？提交后将不可更改！').then(function () {
        row.planStatus = '已审批'
        return updatePlan(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {
        this.getList();
        this.$modal.msgError("提交失败");
      })
    },
    /** 金额格式化 **/
    formatCurrency(number) {
      return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(number);
    },
    /** 选择用户操作 **/
    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    /** 用户选择弹出框 **/
    onUserSelected(obj){
      if(obj !== undefined && obj !== null){
        this.form.salesPerson = obj.nickName;
      }
    },
  }
};
</script>
